package com.gzy.literature.filter;

import com.gzy.literature.dao.BaseDao;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;


@WebServlet("/login")
class LoginFilter extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String account = request.getParameter("account");
        String password = request.getParameter("password");

        BaseDao baseDao = new BaseDao(); // 假设BaseDao有一个无参构造函数或可以通过其他方式获取实例
        try (Connection conn = baseDao.getDataSource().getConnection()) {
            String sql = "SELECT * FROM literature WHERE account = ? AND password = ?";
            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setString(1, account);
                // 注意：这里假设密码已经是以某种方式加密存储的，应该使用相应的验证方法
                // pstmt.setString(2, encryptedPassword(password)); // 示例，需要实现加密函数
                pstmt.setString(2, password); // 仅用于示例，实际应使用加密密码

                try (ResultSet rs = pstmt.executeQuery()) {
                    if (rs.next()) {
                        System.out.println("登录成功");
                        response.sendRedirect("protectedPage.jsp");
                    } else {
                        System.out.println("登录失败");
                        request.setAttribute("error", "账号或密码错误");
                        request.getRequestDispatcher("login.jsp").forward(request, response);
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("数据库错误");
            request.setAttribute("error", "数据库错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}